package com.market.service.impl;

import com.market.entity.Bill;
import com.market.mapper.BillMapper;
import com.market.service.BillService;
import com.market.utils.PageResult;
import com.market.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BillServiceImpl implements BillService {
    private static final Logger logger = LoggerFactory.getLogger(BillServiceImpl.class);
    
    @Autowired
    private BillMapper billMapper;

    @Override
    public List<Bill> findAll() {
        return billMapper.findAll();
    }

    @Override
    public Bill findById(Long id) {
        return billMapper.findById(id);
    }

    @Override
    public List<Bill> findByCondition(String productName, Long providerId, Integer isPayment) {
        return billMapper.findByCondition(productName, providerId, isPayment);
    }
    
    @Override
    public PageResult<Bill> findByConditionPage(String productName, Long providerId, Integer isPayment, 
                                           String billCode, Integer currentPage, Integer pageSize) {
        // 计算偏移量
        Integer offset = (currentPage - 1) * pageSize;
        
        // 查询分页数据
        List<Bill> bills = billMapper.findByConditionPage(productName, providerId, isPayment, billCode, offset, pageSize);
        
        // 查询总记录数
        int totalCount = billMapper.countByCondition(productName, providerId, isPayment, billCode);
        
        // 返回分页结果
        return new PageResult<>(currentPage, pageSize, (long) totalCount, bills);
    }

    @Override
    public Map<String, Object> add(Bill bill) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查账单编码是否已存在
        if (isBillCodeExists(bill.getBillCode())) {
            result.put("flag", false);
            result.put("message", "账单编码 " + bill.getBillCode() + " 已存在，请使用其他编码");
            return result;
        }
        
        // 设置创建时间
        bill.setCreationDate(new java.sql.Timestamp(System.currentTimeMillis()));
        
        // 设置创建者(当前登录用户)
        Long currentUserId = SessionUtil.getCurrentUserId();
        if (currentUserId != null) {
            bill.setCreatedBy(currentUserId);
        } else {
            // 如果无法获取当前用户ID，则设置为默认系统用户ID
            bill.setCreatedBy(1L); // 设置默认管理员ID
        }
        
        try {
            int rows = billMapper.add(bill);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "添加账单成功");
                result.put("data", bill);
            } else {
                result.put("flag", false);
                result.put("message", "添加账单失败");
            }
        } catch (Exception e) {
            logger.error("添加账单出现异常", e);
            result.put("flag", false);
            result.put("message", "添加账单失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> update(Bill bill) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 先查询当前账单信息
            Bill existingBill = billMapper.findById(bill.getId());
            if (existingBill == null) {
                result.put("flag", false);
                result.put("message", "账单不存在，无法更新");
                return result;
            }
            
            // 检查是否为已支付账单
            if (existingBill.getIsPayment() != null && existingBill.getIsPayment() == 2) {
                result.put("flag", false);
                result.put("message", "已支付的账单不能修改");
                return result;
            }
            
            // 检查账单编码是否已被其他账单使用
            if (isBillCodeExistsExcludeId(bill.getBillCode(), bill.getId())) {
                result.put("flag", false);
                result.put("message", "账单编码 " + bill.getBillCode() + " 已被其他账单使用，请更换");
                return result;
            }
            
            // 设置修改时间
            bill.setModifyDate(new java.sql.Timestamp(System.currentTimeMillis()));
            
            // 设置修改者(当前登录用户)
            Long currentUserId = SessionUtil.getCurrentUserId();
            if (currentUserId != null) {
                bill.setModifyBy(currentUserId);
            } else {
                // 如果无法获取当前用户ID，则设置为默认系统用户ID
                bill.setModifyBy(1L); // 设置默认管理员ID
            }
            
            int rows = billMapper.update(bill);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "修改账单成功");
                result.put("data", bill);
            } else {
                result.put("flag", false);
                result.put("message", "修改账单失败，可能账单不存在");
            }
        } catch (Exception e) {
            logger.error("修改账单出现异常", e);
            result.put("flag", false);
            result.put("message", "修改账单失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> deleteById(Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 先查询当前账单信息
            Bill existingBill = billMapper.findById(id);
            if (existingBill == null) {
                result.put("flag", false);
                result.put("message", "账单不存在，无法删除");
                return result;
            }
            
            // 检查是否为已支付账单
            if (existingBill.getIsPayment() != null && existingBill.getIsPayment() == 2) {
                result.put("flag", false);
                result.put("message", "已支付的账单不能删除");
                return result;
            }
            
            int rows = billMapper.deleteById(id);
            if (rows > 0) {
                result.put("flag", true);
                result.put("message", "删除账单成功");
            } else {
                result.put("flag", false);
                result.put("message", "删除账单失败，可能账单不存在");
            }
        } catch (Exception e) {
            logger.error("删除账单出现异常", e);
            result.put("flag", false);
            result.put("message", "删除账单失败: " + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public boolean hasRelatedBills(Long providerId) {
        return billMapper.countByProviderId(providerId) > 0;
    }
    
    @Override
    public boolean isBillCodeExists(String billCode) {
        if (billCode == null || billCode.trim().isEmpty()) {
            return false;
        }
        return billMapper.findByBillCode(billCode) != null;
    }
    
    @Override
    public boolean isBillCodeExistsExcludeId(String billCode, Long id) {
        if (billCode == null || billCode.trim().isEmpty() || id == null) {
            return false;
        }
        return billMapper.findByBillCodeExcludeId(billCode, id) != null;
    }
    
    @Override
    public Map<String, Object> getStatBillCount() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 今日账单数
            int todayCount = billMapper.countTodayBills();
            result.put("todaycount", todayCount);
            
            // 昨日账单数
            int yesterdayCount = billMapper.countYesterdayBills();
            result.put("yesterdaycount", yesterdayCount);
            
            // 本周账单数
            int weekCount = billMapper.countWeekBills();
            result.put("weekcount", weekCount);
            
            // 本月账单数
            int monthCount = billMapper.countMonthBills();
            result.put("monthcount", monthCount);
            
        } catch (Exception e) {
            logger.error("获取账单统计数据出现异常", e);
            throw e;
        }
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getLast7DaysBillCount() {
        try {
            return billMapper.getLast7DaysBillCount();
        } catch (Exception e) {
            logger.error("获取最近7天账单数量趋势出现异常", e);
            throw e;
        }
    }
    
    @Override
    public List<Map<String, Object>> getLast7DaysBillAmount() {
        try {
            return billMapper.getLast7DaysBillAmount();
        } catch (Exception e) {
            logger.error("获取最近7天账单金额趋势出现异常", e);
            throw e;
        }
    }
}
